/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package main

import (
	"gitee.com/tugoer/swagger"
	"net/http"
	"encoding/json"
	"gitee.com/tugoer/examples/projects/swagger/code"
	"fmt"
	"os"
	"log"
)

func main() {
	swagger.API2.Info = &swagger.Info{
		Title:          "Orivil Api Document",
		Description:    "support for OpenApi 2.0",
		Version:        "2.0", // 必须是 2.0, swagger 官方对 3.0 的支持还远远不够
		Contact: &swagger.Contact{
			Name:  "tugoer",
			Url:   "https://gitee.com/tugoer",
			Email: "ksnmmmm@gmail.com",
		},
		License: &swagger.License{
			Name: "MIT",
			Url:  "https://mit-license.org",
		},
	}

	// 文档页面服务, 执行目录必须在 examples 目录下, 否则找不到文件
	fileServer := http.StripPrefix("/api", http.FileServer(http.Dir("public/swagger/dist")))
	http.HandleFunc("/api/", func(writer http.ResponseWriter, request *http.Request) {
		fileServer.ServeHTTP(writer, request)
	})

	// 文档数据服务
	http.HandleFunc("/api-data", func(writer http.ResponseWriter, request *http.Request) {
		json.NewEncoder(writer).Encode(swagger.API2)
	})

	// 表单服务
	http.Handle("/login", code.FormHandler("/login"))

	// 跳转至 API 文档页面
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		http.Redirect(writer, request, "/api", 302)
	})

	port := ":8080"
	fmt.Fprintf(os.Stdout, "listen and serve: http://localhost%s\n", port)
	log.Fatal(http.ListenAndServe(port, nil))
}
